#!/usr/bin/env python

import oauth
import cPickle as p
import os
import urllib2

CONSUMER_KEY = 'EbYpHqB6kvg42KrAIiANA'
CONSUMER_SECRET = '71rIeZof9C5d77jxlm5VTWQNfxJeS7z9Zg0zpjqH1c'

REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'https://twitter.com/oauth/authorize'

def CreateMap(filename,object):
    try:
        f = open(filename,'w')
        p.dump(object,f)
        f.close()
        return True
    except Exception,e:
        print e
        return False
    
def LoadMap(filename):
    try:
        f = open(filename)
        obj = p.load(f)
        f.close()
        return obj
    except Exception,e:
        print e    
        return

class simpleoauth(object):
    def __init__(self,access_token=None):
        self._access_token = access_token
        self._Consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()

    def _FetchUrl(self,
                    url,
                    post_data=None,
                    parameters=None):
        if post_data: http_method = "POST"
        else: http_method = "GET"

        oauth_req = self._makeOAuthRequest(url,http_method=http_method)
        oauth_req.sign_request(self._signature_method, self._Consumer, self._access_token)

        argStr = ""
        argData = None
        
        if post_data:
            argData = oauth_req.to_postdata()
        else:
            argStr = "?%s" %(oauth_req.to_postdata())

        req = urllib2.Request("%s%s" %(url, argStr),argData, {})
    
        handle = urllib2.urlopen(req)
        return handle.read()

    def _makeOAuthRequest(self, url, token=None,parameters=None, http_method="GET"):
        if not token: token = self._access_token
        request = oauth.OAuthRequest.from_consumer_and_token(self._Consumer, token=token,http_url=url, parameters=parameters,http_method=http_method)
        return request

    def getAccessToken(self, url=ACCESS_TOKEN_URL):
        token = self._FetchUrl(url)
        return oauth.OAuthToken.from_string(token) 

    def getRequestToken(self, url=REQUEST_TOKEN_URL):
        resp = self._FetchUrl(url)
        token = oauth.OAuthToken.from_string(resp)
        return token

    def getAuthorizationURL(self, token, url=AUTHORIZATION_URL):
        oauth_req = self._makeOAuthRequest(url, token=token)
        oauth_req.sign_request(self._signature_method, self._Consumer, self._access_token)
        return oauth_req.to_url()
    
    def getrequest(self,url,parameters,http_method):
        oauth_req = self._makeOAuthRequest(url,parameters=parameters,http_method=http_method)
        oauth_req.sign_request(self._signature_method, self._Consumer, self._access_token)
        return oauth_req.to_postdata()
      
def main():
    if os.path.exists("access_token") == False:
        if os.path.exists("request_token") == False:
            oauth = simpleoauth()
            request_token = oauth.getRequestToken()
            authorization_url = oauth.getAuthorizationURL(request_token)
            CreateMap("request_token",request_token)
            print authorization_url
        else:
            request_token = LoadMap("request_token")
            oauth = simpleoauth(request_token)
            access_token = oauth.getAccessToken() 
            CreateMap("access_token",access_token)
    else:
        pass
    
if __name__=='__main__' :
    main()
